<template>
  <div class="sidebar">
    <el-menu class="sidebar-el-menu" :default-active="onRoutes" :collapse="collapse" background-color="#324157" text-color="#bfcbd9" active-text-color="#20a0ff" unique-opened router>
      <template v-for="item in items">
        <template v-if="item.subs">
          <el-submenu :index="item.index" :key="item.index">
            <template #title>
              <i :class="item.icon"></i>
              <span>{{ item.title }}</span>
            </template>
            <template v-for="subItem in item.subs">
              <el-submenu v-if="subItem.subs" :index="subItem.index" :key="subItem.index">
                <template #title>{{ subItem.title }}</template>
                <el-menu-item v-for="(threeItem, i) in subItem.subs" :key="i" :index="threeItem.index">{{ threeItem.title }}</el-menu-item>
              </el-submenu>
              <el-menu-item v-else :index="subItem.index" :key="subItem.index">{{ subItem.title }}</el-menu-item>
            </template>
          </el-submenu>
        </template>
        <template v-else>
          <el-menu-item :index="item.index" :key="item.index">
            <i :class="item.icon"></i>
            <template #title>{{ item.title }}</template>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script>
// import bus from "../common/bus";
export default {
  data() {
    return {
      originalItems: [
        {
          icon: 'el-icon-lx-group',
          index: 'user',
          title: '用户管理',
          subs: [
            { index: 'userControl', title: '前端用户管理' },
            { index: 'adminUser', title: '后台用户管理' },
            { index: 'powerAudit', title: '商家审核' },
          ],
        },
        {
          icon: 'el-icon-document',
          index: 'content',
          title: '内容管理',
          subs: [
            {
              title: '动态管理',
              index: 'moments',
              subs: [
                { index: 'blogTopic', title: '动态话题' },
                { index: 'blogReply', title: '动态评论' },
                { index: 'momentsManagement', title: '动态管理' },
              ],
            },
            {
              icon: 'el-icon-chat-dot-round',
              index: 'community',
              title: '社区管理',
              subs: [
                { index: 'forumTopic', title: '帖子话题' },
                { index: 'communityClassification', title: '社区分类' },
                { index: 'communityManagement', title: '社区管理' },
                { index: 'postClassification', title: '帖子分类' },
                { index: 'forumReply', title: '帖子评论' },
                { index: 'postManagement', title: '帖子管理' },
              ],
            },
            {
              title: '活动',
              index: 'activity',
              subs: [
                { index: 'activityManagement', title: '活动管理' },
                { index: 'activityOrder', title: '活动订单' },
              ],
            },
          ],
        },
        {
          icon: 'el-icon-lx-goods',
          index: '8',
          title: '自营商城',
          subs: [
            { index: 'zyMallClass', title: '自营商城分类' },
            { index: 'zyMallCommodity', title: '自营商城商品' },
            { index: 'zyMallOrder', title: '自营商城订单' },
            { index: 'zyMallPartition', title: '自营分区' },
            { index: 'zyMallRefund', title: '自营商城退款' },
            { index: 'freight', title: '运费模板' },
          ],
        },
        {
          icon: 'el-icon-lx-recharge',
          index: 'regimen',
          title: '养生',
          subs: [
            { index: 'regimenClass', title: '养生分类' },
            { index: 'regimenContent', title: '养生内容' },
          ],
        },
        {
          icon: 'el-icon-lx-recharge',
          index: 'cyBer',
          title: '资金明细',
        },
      ],
      items: [], // 过滤后的菜单项
    }
  },
  computed: {
    onRoutes() {
      return this.$route.path.replace('/', '')
    },
    collapse() {
      return this.$store.state.collapse
    },
  },
  created() {
    // console.log('原始路由:', this.$router.options.routes[0].children)
    // console.log('原始菜单项:', this.originalItems)

    this.items = this.filterMenuByRoutes(this.originalItems)
    // console.log('过滤后的菜单项:', this.items)
  },
  methods: {
    /**
     * 根据路由权限过滤菜单项
     * @param {Array} items - 菜单配置数组
     * @param {Array} userRoutes - 用户拥有的路由权限（可选，默认使用内置配置）
     * @returns {Array} 过滤后的菜单配置
     */
    filterMenuByRoutes(items) {
      // 使用传入的路由或默认路由
      const routes = this.$router.options.routes[0].children

      // 创建路由路径集合，便于快速查找
      const routePaths = new Set(routes.map((route) => route.path))

      console.log('可用路由路径:', Array.from(routePaths)) // 调试用

      /**
       * 递归过滤菜单项
       * @param {Array} menuItems - 当前层级的菜单项
       * @returns {Array} 过滤后的菜单项
       */
      const filterItems = (menuItems) => {
        const result = []

        for (const item of menuItems) {
          // 深拷贝当前项，避免修改原始数据
          const clonedItem = { ...item }

          // 如果有子菜单，递归处理
          if (clonedItem.subs && clonedItem.subs.length > 0) {
            // 递归过滤子菜单
            const filteredSubs = filterItems(clonedItem.subs)
            // console.log(`父级菜单 "${clonedItem.title}" 过滤后的子菜单数量:`, filteredSubs.length);

            // 如果过滤后还有子菜单，则保留该父级菜单
            if (filteredSubs.length > 0) {
              clonedItem.subs = filteredSubs
              result.push(clonedItem)
            }
            // 如果没有子菜单了，则不显示该父级菜单
          } else {
            // 叶子节点，检查路由权限
            const fullPath = `/${clonedItem.index}`
            const hasPermission = routePaths.has(fullPath)
            // console.log(`检查路由权限: "${clonedItem.title}" (${fullPath}) -> ${hasPermission}`);

            if (hasPermission) {
              result.push(clonedItem)
            }
          }
        }

        return result
      }

      return filterItems(JSON.parse(JSON.stringify(items))) // 深拷贝避免修改原始数据
    },
  },
}
</script>

<style scoped>
.sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 70px;
  bottom: 0;
  overflow-y: scroll;
}

.sidebar::-webkit-scrollbar {
  width: 0;
}

.sidebar-el-menu:not(.el-menu--collapse) {
  width: 250px;
}

.sidebar > ul {
  height: 100%;
}
</style>
